"use client";
import "./index.css";
import React, { useEffect, useState } from "react";
import ReactECharts from "echarts-for-react";
import dayjs from "dayjs";
import { getUserSignInRecordUsingGet } from "@/api/userController";
import { message } from "antd";

/**
 * 日历图
 * @constructor
 */
export default function CalendarChart() {
  // 签到日期列表（[1, 200]，表示第 1 和第 200 天有签到记录）
  const [dataList, setDataList] = useState<number[]>([]);
  //  当前是第几年
  const year = new Date().getFullYear();
  //  从后端取数据
  const optionsDate = dataList.map((dayOfYear) => {
    //  计算日期字符串
    const dateStr = dayjs(`${year}-01-01`)
      .add(dayOfYear - 1, "day")
      .format("YYYY-MM-DD");
    return [dateStr, 1];
  });

  //  请求后端获取数据
  const fetchDataList = async () => {
    try {
      const res = await getUserSignInRecordUsingGet({ year });
      // @ts-ignore
      setDataList(res.data);
    } catch (e) {
      // @ts-ignore
      message.error("获取签到记录失败," + e.message);
    }
  };

  //  只调用一次接口
  useEffect(() => {
    fetchDataList();
  }, []);

  const options = {
    visualMap: {
      show: false,
      min: 0,
      max: 1,
      type: "piecewise",
      orient: "horizontal",
      left: "center",
      inRange: {
        //  渐变色
        color: ["#DCFFFD", "#fad4d0", "#c8d7ff"],
      },
    },
    calendar: {
      top: 120,
      left: 30,
      right: 30,
      cellSize: ["auto", 16],
      range: year,
      itemStyle: {
        borderWidth: 0.5,
      },
      yearLabel: {
        position: "top",
        formatter: `${year}年学习记录`,
      },
    },
    series: {
      type: "heatmap",
      coordinateSystem: "calendar",
      data: optionsDate,
    },
  };

  return <ReactECharts className="calendar-chart" option={options} />;
}
